import { TokenStorage } from "../utils/storageSevice.js";
import { API_URL, UPLOAD_URL, ISDEBUG } from "../utils/globalConstant.js";
import {common} from "../utils/common.js";
import { CACHE} from "../utils/cache.js";

//统一请求的http服务
function HttpService(url, param, completeCallback){
  let token = TokenStorage.getData();
  param['accessToken']=token?token:'';
  let promise = new Promise((resolve, reject)=> { 
    const requestTask = wx.request({
      url: API_URL+url,
      method: 'POST',
      data:param,
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        if (ISDEBUG) console.log("请求地址为：" + API_URL + url)
        if (ISDEBUG) console.log("请求参数为：" + JSON.stringify(param))
        if (ISDEBUG) console.log("请求回来的数据:");
        if (ISDEBUG) console.log(res);
        if (res.statusCode == 401 && res.data == "没有登录"){
          wx.showModal({
            title: '提示',
            content: '访问服务器失败',
            showCancel: false
          })
          return;
        }
        resolve(res.data);
      },
      fail: function (err) {//失败回调
        if (ISDEBUG) console.log("请求失败的地址:" + API_URL + url );
        if (ISDEBUG) console.log("失败后的信息:" + err);
        reject(err);
      },
      complete: function (res) {//接口调用结束的回调函数（调用成功、失败都会执行）
        completeCallback && completeCallback();
      }
    })
  })
  return promise;
}

function HttpUploadService(url, param, filePath, fileName, completeCallback) {
  let token = TokenStorage.getData();
  param['accessToken'] = token ? token : '';
  let promise = new Promise((resolve, reject) => {
    const uploadReqTask = wx.uploadFile({
      url: UPLOAD_URL + url,
      filePath: filePath,
      name: fileName,
      method: 'POST',
      formData: param,
      header: {
        "Content-Type": "multipart/form-data" 
      },
      success: function (res) {
        if (ISDEBUG) console.log("请求地址为：" + UPLOAD_URL + url)
        if (ISDEBUG) console.log("请求参数为：" + JSON.stringify(param))
        if (ISDEBUG) console.log("请求回来的数据:");
        if (ISDEBUG) console.log(res);
        if (res.statusCode == 401 && res.data == "没有登录") {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
          return;
        }
        resolve(JSON.parse(res.data))
      },
      fail: function (err) {//失败回调
        if (ISDEBUG) console.log("请求失败的地址:" + UPLOAD_URL + url);
        if (ISDEBUG) console.log("失败后的信息:" + err);
        reject(err);
      },
      complete: function (res) {//接口调用结束的回调函数（调用成功、失败都会执行）
        completeCallback && completeCallback();
      }
    })
  })
  return promise;
}

module.exports = {
  HttpService: HttpService,
  HttpUploadService: HttpUploadService
}